package com.yf.ccdugtfood.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yf.ccdugtfood.R;
import com.yf.ccdugtfood.bean.Status;
import com.yf.ccdugtfood.util.Constant;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 注册活动
 */
public class RegisterActivity extends AppCompatActivity implements View.OnClickListener {
    private TextView tv_back, tv_title;                                   //后退键，标题栏
    private EditText re_userName, re_userPhone, re_password, re_passwords;  //姓名，手机号码，密码，确认密码
    private Button btn_register;                                             //注册按钮
    private String user_name, password, user_phone;
    private String passwords;
    public static final int MSG_SUCCESS_OK = 2;
    private Type typeList;
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            if (msg.what==MSG_SUCCESS_OK){
                if (msg.obj!=null){
                    String status = msg.obj.toString();
                    if ("SUCCESS".equals(status.trim())){
                        Toast.makeText(RegisterActivity.this,"注册成功！",Toast.LENGTH_SHORT).show();
                        finish();
                    }else {
                        Toast.makeText(RegisterActivity.this,"注册失败！",Toast.LENGTH_SHORT).show();
                    }
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        init();
    }

    private void init() {
        tv_back = (TextView) findViewById(R.id.tv_back);
        tv_title = (TextView) findViewById(R.id.tv_title);
        re_userName = (EditText) findViewById(R.id.re_userName);
        re_userPhone = (EditText) findViewById(R.id.re_userPhone);
        re_password = (EditText) findViewById(R.id.re_password);
        re_passwords = (EditText) findViewById(R.id.re_passwords);
        btn_register = (Button) findViewById(R.id.btn_register);
        btn_register.setOnClickListener(this);
        tv_title.setText("注册会员");
        tv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    /**
     * 注册事件监听
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_register:
                user_name = re_userName.getText().toString().trim();
                user_phone = re_userPhone.getText().toString().trim();
                password = re_password.getText().toString().trim();
                passwords = re_passwords.getText().toString().trim();
                if (user_name.isEmpty()) {
                    Toast.makeText(this, "请输入您的名字！", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (user_phone.isEmpty()) {
                    Toast.makeText(this, "请输入您的手机号码，用于登录账号！", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (password.isEmpty()) {
                    Toast.makeText(this, "请输入您的账号密码！", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (passwords.isEmpty()) {
                    Toast.makeText(this, "请再次输入您的密码！", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (!password.equals(passwords)) {
                    Toast.makeText(this, "两次输入密码不一致，请重新输入！", Toast.LENGTH_SHORT).show();
                    return;
                }
                String url = Constant.WEB_SITE+Constant.REQUEST_REGISTER_URL;
                OkHttpClient okHttpClient = new OkHttpClient();
                RequestBody body = new FormBody.Builder()
                        .add("user_name",user_name)
                        .add("user_phone",user_phone)
                        .add("password",password)
                        .add("role","0")
                        .build();
                Request request = new Request.Builder()
                        .url(url)
                        .post(body)
                        .build();
                final Call call = okHttpClient.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String result = response.body().string();
                        Log.i("re",result);
                        Message msg = new Message();
                        msg.what = MSG_SUCCESS_OK;
                        msg.obj = result;
                        handler.sendMessage(msg);
                    }
                });
                /*new Thread(){
                    @Override
                    public void run() {
                        try {
                            user_name_out = re_userName.getText().toString();
                            user_phone_out = re_userPhone.getText().toString();
                            password_out = re_password.getText().toString();
                            String data = "user_name="+ URLEncoder.encode(user_name_out,"utf-8")
                                    +"&user_phone="+URLEncoder.encode(user_phone_out,"utf-8")
                                    +"&password="+URLEncoder.encode(password_out,"utf-8");
                            URL url = new URL(Constant.WEB_SITE+Constant.REQUEST_REGISTER_URL);
                            HttpURLConnection coon = (HttpURLConnection) url.openConnection();
                            // 设置允许输出
                            coon.setDoOutput(true);
                            coon.setRequestMethod("POST");
                            coon.setConnectTimeout(10000);
                            // 设置不用缓存
                            coon.setUseCaches(false);
                            coon.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                            coon.setRequestProperty("Content-Length", data.length()+"");
                            coon.setDoOutput(true);
                            // 开始连接请求
                            coon.connect();
                            OutputStream os = coon.getOutputStream();
                            os.write(data.getBytes());
                            int responseCode = coon.getResponseCode();
                            if (responseCode==200){
                                BufferedReader reader = new BufferedReader(new InputStreamReader((coon.getInputStream()),"utf-8"));
                                StringBuilder sb= new StringBuilder();
                                String line;
                                while ((line=reader.readLine())!=null){
                                    line = new String(line.getBytes(),"utf-8");
                                    sb.append(line);
                                }
                                Log.i("aa",new String(sb));
                                Message msg = handler.obtainMessage();
                                msg.what = MSG_SUCCESS_OK;
                                msg.obj = sb;
                                handler.sendMessage(msg);
                            }
                            coon.disconnect();
                        }catch (IOException e){
                            e.printStackTrace();
                        }
                    }
                }.start();*/
                break;
            default:
                break;
        }
    }
}







